//
//  NSObjectExtension.swift
//  UITableViewDemo
//
//  Created by daqsoft-mac on 2022/5/12.
//

import Foundation

/// 数据绑定Key
private var objectDataKey : Void?

/// Controller绑定Key
private var objectViewControllerKey : Void?

extension NSObject {
    
    /// 绑定的数据
    var objectData : Any? {
        get {
            return objc_getAssociatedObject(self, &objectDataKey)
        }
        
        set {
            objectDataWillChange()
            objc_setAssociatedObject(self, &objectDataKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            objectDataDidChange()
        }
    }
    
    /// 绑定的Controller
    var objectViewController : Any? {
        get {
            return objc_getAssociatedObject(self, &objectViewControllerKey)
        }
        
        set {
            objc_setAssociatedObject(self, &objectViewControllerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

@objc extension NSObject {
    
    /// 绑定的数据已经改变
    func objectDataDidChange() { }
    
    /// 绑定的数据将要改变
    func objectDataWillChange() { }
    
    /// 标志符
    /// - Returns: 类名+ID作为标志符
    static func identifierString() -> String {
        return NSStringFromClass(self).appending("ID") as String
    }
}
